package com.ss;

//import com.google.android.samples.graphics.Xfermodes.SampleView;


import com.ss.Line;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
//import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class ChartActivity extends Activity {
    /** Called when the activity is first created. */
	private static String myTicker="INTC";
	public static java.util.List myList ;
	//public static int array_count ;
	       static int  MAX_ARRAY_COUNT = 3000 ;
	       //Line line_array[]=new Line[MAX_ARRAY_COUNT]; 
	     

	
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        
        try {
        	
       
        //setContentView(R.layout.main);
        Bundle extras = getIntent().getExtras();  
        if (extras != null) {
            myTicker = extras.getString("Ticker");
        }   
        System.out.println("Chart: In onCreate for ticker=" +  myTicker);
        FileOutputStream fos = this.openFileOutput(myTicker +".csv", 0);
        FileOutputStream fos_1 = this.openFileOutput(myTicker +"_1.csv", 0);
        SimpleDateFormat formatter =  
            new SimpleDateFormat("yyyy/MM/dd"); 

        Date dt = new Date(System.currentTimeMillis());

		String yyyy_mm_dd = (formatter.format(dt) )  ;
		String curr_year = yyyy_mm_dd.substring(0,4) ;
		String curr_month = yyyy_mm_dd.substring(5,7) ;
		String curr_date = yyyy_mm_dd.substring(8,10) ;
        // Go Back 5 Years
        int int_from_year =  Integer.parseInt( curr_year ) - 5 ;
        Log.i("ChartActivity:","Before getData");
        //OutputStream os = getAssets().
        Line line_array[]=null;
        line_array=getData(myTicker,curr_month, curr_date, int_from_year, curr_year,fos,fos_1 );
        setContentView(new ChartIt(this, line_array));
        }
        catch (Exception ex)
        {
        	
        	Log.i("ChartActivity", "caught " + ex.getMessage());
        	ex.printStackTrace();
        }
    }
    
    
    private static Line[] getData(String TickerSymbol
    		                          ,String curr_month 
    		                          ,String curr_date
    		                          ,int int_from_year
    		                          ,String curr_year
    		                          ,FileOutputStream destination
    		                          ,FileOutputStream fos_1
    		                          ) 
    {
    	Line line_array[]=null;
    	try {
                           String TargetUrl =    "http://chart.yahoo.com/table.csv?s=" + TickerSymbol +
                                                 "&a="
                                                 + curr_month
                                                 + "&b="
                                                 + curr_date
                                                 + "&c="
                                                 + int_from_year  
                                                 + "&d="
                                                 + curr_month
                                                 + "&e="
                                                 + curr_date
                                                 + "&f="
                                                 + curr_year
                                                 + "&g=w&q=q&y=0&z="
                                                 +
                                                 TickerSymbol + "&x=.csv"
                                                  ;


            

                           URL url = new URL( TargetUrl);
                   	URLConnection connection = url.openConnection();

                            System.out.println("TargetUrl  is:"
                                                   + TargetUrl);



                           BufferedInputStream in = (
                                                   new BufferedInputStream(
                                                   connection.getInputStream()));

                           byte[] buffer = new byte[8192] ;
                          StringBuffer strbuf = new StringBuffer( 8192 ) ;
 
                           while ( true )
                           {
                             //   System.out.println(inputLine);
                            int bytes_read = in.read( buffer) ;
                            if ( bytes_read == -1 ) break ;
                          
                               destination.write(buffer , 0, bytes_read ) ;
                               System.out.println("Downloaded " + bytes_read+ " bytes for ticker " +
                                      TickerSymbol );
                              strbuf.append( new String( buffer , 0, bytes_read ) ) ;

                            }

                   	       in.close();
                           destination.close() ;

                           line_array=change_string(strbuf , TickerSymbol, fos_1 ) ;
                }catch (Exception ex)
                {
                ex.printStackTrace();
                Log.i("ChartActivity", "caught " + ex);
                // showMessage(e.getMessage());
                }
                return line_array;
    }
    
    public static Line[] change_string ( StringBuffer strbuf,
            String TickerSymbol,
            FileOutputStream fos_1
            )
    {
			int pos1, pos2, pos3, pos4, pos5 ;
			int length = 0 ;
			int array_count=0;
			Line line_array[]= new Line[MAX_ARRAY_COUNT];
			/*
			if ( array_count >= MAX_ARRAY_COUNT )
			{
			System.out.println("MAX_ARRAY_COUNT reached "+ array_count +"\n ") ;
			return line_array;
			}
			*/
			// Manipulate this string
			String s1 = new String ( strbuf.toString() )  ;
			StringTokenizer tokens = new
			            StringTokenizer( s1, "\n" ) ;
			StringBuffer s2_buf = new  StringBuffer( ) ;
			StringBuffer actual_line_buf = new StringBuffer() ;
			
			
			tokens.nextToken() ;
			while ( tokens.hasMoreTokens() )
			{
			String curr_line = new String ( tokens.nextToken() ) ;
			pos1 = curr_line.indexOf( ',', 1) + 1 ;
			pos2 = curr_line.indexOf( ',', pos1 ) +1  ;
			pos3 = curr_line.indexOf( ',', pos2 )+ 1  ;
			pos4 = curr_line.indexOf( ',', pos3 ) + 1  ;
			pos5 = curr_line.indexOf( ',', pos4 ) + 1  ;
			length = curr_line.length() ;
			
			if ( array_count >= MAX_ARRAY_COUNT )
			{
				System.out.println("MAX_ARRAY_COUNT reached "+ array_count +"\n ") ;
				break;
			}
			
			// 0 to pos1 -1 because we do not want the comma
			line_array[ array_count ] = new Line(
			    TickerSymbol ,
			    curr_line.substring( 0,(pos1 -1 ) ),
			    curr_line.substring( pos1,(pos2 - 1) ),
			    curr_line.substring( pos2,(pos3-1 ) ),
			    curr_line.substring( pos3,(pos4-1)),
			    curr_line.substring( pos4,(pos5-1)),
			    curr_line.substring( pos5,length)
			       ) ;
			
			array_count++ ;
			
			
			
			actual_line_buf.append ( curr_line.substring( 0,pos1) ) ;
			actual_line_buf.append ( curr_line.substring( pos2 , pos3) ) ;
			actual_line_buf.append ( curr_line.substring( pos3 , pos4) ) ;
			actual_line_buf.append ( curr_line.substring( pos5 , length) ) ;
			actual_line_buf.append ( "\n" ) ;
			
			
			s2_buf.insert( 0 , actual_line_buf.toString() ) ;
			
			
			actual_line_buf.delete(0 , (length + 1) ) ;
			// System.out.println("actual_line "+ actual_line_buf.toString() +"\n ") ;
			
			
			
			}
			try
			{
			// System.out.println("s2_buf "+ s2_buf.toString() +"\n ") ;
			
			
			BufferedWriter    destination_1 =
			new BufferedWriter(
			new  OutputStreamWriter( fos_1));
			//new FileOutputStream(TickerSymbol +"_1.csv")) ) ; 
			
			destination_1.write(s2_buf.toString() , 0, s2_buf.toString().length() ) ;
			destination_1.flush() ;
			destination_1.close() ;
			
			}
			catch ( IOException io )
			{
			System.out.println("Error opening output file \n ") ;
			}

    return line_array;
    } // End change_string

      
 } // End Class
